<?php

/**
 * 后台IP限制列表
 * File Name：AllowIp.php
 * File Encoding：UTF-8
 * File New Time：2014-5-27 9:18:59
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class AllowIp extends BaseModel {

    public function tableName() {
        return '{{allow_ip}}';
    }

    public function rules() {
        return array(
            array('ip', 'required', 'message' => 'ip地址不能为空！'),
            //array('ip', 'unique', 'allowEmpty' => false, 'message' => '该ip地址已经存在！'),
            //安全的。。。
            array('status,create_time,create_ip', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 获取IP列表
     * @param type $isCache 是否使用缓存
     * @return boolean
     */
    public function getIpList($isCache = true) {
        $cache = array();
        $key = 'AllowIp_getIpList';
        //清理缓存
        if (!$isCache) {
            Yii::app()->cache->delete($key);
        }
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $data = $this->findAll($this->where(array('status' => 1, 'select' => 'ip', 'order' => 'id desc')));
            if (empty($data)) {
                return false;
            }
            $cache = array();
            foreach ($data as $rs) {
                $cache[] = $rs->ip;
            }
            //默认缓存3600秒
            Yii::app()->cache->set($key, $cache, 3600);
        }
        return $cache;
    }

    /**
     * 添加IP
     * @param type $ip
     * @return boolean
     */
    public function addIp($ip = '') {
        if (empty($ip)) {
            $ip = GuestDataModel::model()->getForwardedForIp();
        }
        $old = $this->find($this->where(array('ip' => $ip)));
        if (!empty($old)) {
            $old->status = 1;
            if ($old->save(false)) {
                return true;
            }
        }
        $this->ip = $ip;
        $this->status = 1;
        $this->setIsNewRecord(true);
        if ($this->validate() && $this->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 当前用户是否在允许IP列表中
     * @return boolean
     */
    public function allowIpList() {
        $allowIp = $this->getIpList();
        $allowIp = empty($allowIp) ? array() : $allowIp;
        if (in_array(GuestDataModel::model()->getForwardedForIp(), $allowIp)) {
            return true;
        }
        return false;
    }

    //数据保存前操作
    protected function beforeSave() {
        //是否新增
        if ($this->isNewRecord) {
            $this->create_time = time();
            $this->create_ip = GuestDataModel::model()->getForwardedForIp();
        } else {
            
        }
        return true;
    }

    //数据保存后回调
    protected function afterSave() {
        $this->getIpList(false);
    }

}
